const hx = require('hbuilderx');
const hxTheme = require('./theme.js')

class MessageHandler {
	constructor(uwebView) {
		this.uwebView = uwebView;
		this.onMessage()
	}
	static instance = null;
	static getInstance(uwebView) {
		try{
			if (MessageHandler.instance === null) {
				MessageHandler.instance = new MessageHandler(uwebView);
			}
		}catch(err){
			console.log('错误',err)
		}
		return MessageHandler.instance
	}

	handler(data) {
		if (!data || !data.command) return;
		switch (data.command) {
			case 'initApp':
				console.log('发送初始化设置')
				this.initApp()
				break;
			case 'writeClipboard':
				this.writeClipboard(data.data)
				break;
			case 'insertCode':
				this.insertCode(data.data)
				break;
			case 'updateModelName':
				this.updateModelName(data.data)
				break;
			case 'getProjectInfo':
				this.getProjectInfo()
				break;
			default:
				break;
		}
	}

	initApp() {
		let ThemeColorData = hxTheme.getHBuilderXThemeData();
		const config = require('./config.js')
		this.uwebView.postMessage({
			"command": "initApp",
			"data": {
				themeInfo: ThemeColorData,
				apiKey: config.getData('apiKey'),
				baseUrl: config.getData('baseUrl'),
				modelName: config.getData('chatModelName')
			}
		});
	}


	writeClipboard(content) {
		hx.env.clipboard.writeText(content);
	}
	async insertCode(content) {
		try {
			const activeTextEditor = await hx.window.getActiveTextEditor()
			if (!activeTextEditor) {
				console.warn('没有活动的文本编辑器');
				return;
			}

			activeTextEditor.edit((editBuilder => {
				const selection = activeTextEditor.selection;
				// const document = activeTextEditor.document
				// 获取选中的内容
				// const selectionText = document.getText(selection)
				editBuilder.replace(selection, content)
			}));
		} catch (error) {
			console.error('插入代码失败:', error);
			hx.window.showErrorMessage('插入代码失败: ' + error.message);
		}

	}
	updateModelName(content){
		const config = hx.workspace.getConfiguration("ucoder");
		config.update('chatModelName',content)
	}
	
	async getProjectInfo(){
		const activeTextEditor = await hx.window.getActiveTextEditor()
		if(activeTextEditor!=undefined){
			const document = activeTextEditor.document
			this.uwebView.postMessage({
				"command": "projectInfo",
				"data": document
			})
		}
	}
	
	onMessage(){
		this.uwebView.onDidReceiveMessage((msg)=>{
			console.log('收到web消息')
			this.handler(msg)
		});
	}
	
	postMessage(msg){
		console.log('向web发送消息')
		this.uwebView.postMessage(msg);
	}

}


module.exports = MessageHandler